package SqlGenerator;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.util.Date;

public class ColumnInfo {
    private String columnName;
    private Class<?> type;
    private boolean isID=false;
    private boolean nullable=true;
    private int length=32;
    private boolean needPersist=false;

    public String getColumnName() {
        return columnName;
    }

    public ColumnInfo parse(Field field)
    {
        this.columnName = field.getName();
        this.type = field.getType();
        Annotation[] annotations = field.getDeclaredAnnotations();
        for(Annotation annotation:annotations)
        {
            if(annotation.annotationType().equals(Column.class)){
                this.needPersist = true;
                Column column = (Column)annotation;
                if(!column.value().equals("")){
                    this.columnName = column.value();
                }
                this.nullable = column.nullable();
                if(column.length()!=-1){
                    this.length=column.length();
                }
            }
            else if(annotation.annotationType().equals(ID.class)){
                this.needPersist=true;
                ID id=(ID)annotation;
                this.isID=true;
                if(!id.value().equals("")){
                    this.columnName = id.value();
                }
            }
        }
        if(this.needPersist)
            return this;
        else
            return null;
    }
    //sql语句转换
    public String toString() {
        StringBuilder sql = new StringBuilder(columnName);
        if(this.type.equals(String.class)){
            sql.append(" VARCHAR("+this.length+")");
        }
        else if(this.type.equals(Integer.class)){
            sql.append(" INT");
        }
        else if(this.type.equals(BigInteger.class)){
            sql.append(" bigint("+this.length+")");
        }
        else if(this.type.equals(Date.class)){
            sql.append(" Date");
        }
        else if (this.type.equals(Double.class)){
            sql.append(" double("+(this.length-2)+",2)");
        }
        if(this.isID){
            sql.append(" PRIMARY KEY");
        }
        if(!this.nullable){
            sql.append(" NOT NULL");
        }
        sql.append(",");
        return sql.toString();
    }
}
